<?php

namespace lxs\tools;

use Carbon\Carbon;
use lxs\config\System;

class Tools
{

    public static function dump($value)
    {
        echo '<pre>' . print_r($value, true) . '</pre>';
    }

    /**
     * 获取或配置系统参数
     * @param string $name 参数名称
     * @param mixed|null $value 参数内容
     * @return mixed
     */
    public static function Config(string $name = '', mixed $value = null): mixed
    {
        if (is_null($value) && is_string($name)) {
            try {
                return System::instance()->get($name);
            } catch (\Exception $ex) {
                return null;
            }
        } else {
            try {
                return System::instance()->set($name, $value);
            } catch (\Exception $ex) {
                return false;
            }
        }
    }

    /**
     * 时间格式转换
     */
    public static function timeConvert($time, $format='Y-m-d H:i:s'): float|bool|int|string
    {
        if (is_numeric($time) && $time > 0) {
            return date($format, $time);
        } else if (strtotime($time) !== false) {
            return Carbon::parse($time)->timestamp;
        } else {
            return '';
        }
    }


    /**
     * 生成唯一编码
     * @return string
     */
    public static function uniqidDate($name, $number = 1): string
    {

        $numbers = range(0, 9);
        shuffle($numbers);
        $num = 3;
        $random = implode('', array_slice($numbers, 0, $num));
        (string)$code = $random . date('YmdHis') . uniqid();

        if ($number > 0) {
            if (strlen($number) > 1) {
                $length = strlen($number) - 1;
                $code = substr($code, $length) . $number;
            } else {
                $code .= $number;
            }
        } else {
            $code .= rand(0, 9);
        }
        return $name . $code;
    }



    //无限极分类
    public static function getTree($data, $pid = 0, $level = 0)
    {
        $arr = [];
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                $v['level'] = $level;
                $v['children'] = self::getTree($data, $v['id'], $level + 1);
                $arr[] = $v;
            }
        }
        return $arr;
    }

}
